import React, { Component } from 'react'
import FooterTodo from './components/FooterTodo'
import HeaderTodo from './components/HeaderTodo'
import ListTodo from './components/ListTodo'
import { nanoid } from 'nanoid'
import { setLocal, getLocal } from './utils/localStorage'

class App extends Component {
  state = {
    list: getLocal() || [],
    active: 'all',
  }

  //设置本地存储
  componentDidUpdate = () => {
    const { list } = this.state
    setLocal(list)
  }

  //新增
  addItem = (name) => {
    this.setState({
      list: [
        {
          name,
          id: nanoid(),
          done: false,
        },
        ...this.state.list,
      ],
    })
  }

  //修改属性
  editTodo = (id, type, value) => {
    const { list } = this.state
    this.setState({
      list: list.map((item) =>
        item.id === id ? { ...item, [type]: value } : item
      ),
    })
  }

  //全选
  editAllTodo = (done) => {
    const { list } = this.state
    this.setState({
      list: list.map((item) => {
        return { ...item, done }
      }),
    })
  }
  //删除
  handleDel = (id) => {
    const { list } = this.state
    if (id) {
      this.setState({
        list: list.filter((item) => item.id !== id),
      })
    } else {
      this.setState({
        list: list.filter((item) => !item.done),
      })
    }
  }

  editActive = (active) => {
    this.setState({
      active,
    })
  }

  render() {
    const { list, active } = this.state
    return (
      <section className="todoapp">
        <HeaderTodo addItem={this.addItem} />
        <ListTodo
          list={list}
          editTodo={this.editTodo}
          editAllTodo={this.editAllTodo}
          handleDel={this.handleDel}
          active={active}
        />
        <FooterTodo
          itemsLeft={list.filter((item) => !item.done).length}
          handleDel={this.handleDel}
          active={active}
          editActive={this.editActive}
          clearBtn={list.some((item) => item.done)}
        />
      </section>
    )
  }
}

export default App
